package com.rahms.server.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rahms.common.constant.MessageConstant;
import com.rahms.common.result.R;
import com.rahms.pojo.entity.User;
import com.rahms.server.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/user")
@Tag(name = "用户管理", description = "用户信息管理相关接口")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @Autowired(required = false)
    private PasswordEncoder passwordEncoder;
    
    /**
     * 获取用户信息
     */
    @GetMapping("/me")
    @Operation(summary = "获取当前用户信息", description = "根据用户ID获取当前登录用户的详细信息")
    public R<User> getCurrentUser(@Parameter(description = "用户ID", required = true) @RequestParam Long userId) {
        User user = userService.getUserById(userId);
        return user != null ? R.success(user) : R.error(MessageConstant.USER_NOT_EXIST);
    }
    
    /**
     * 更新用户信息
     */
    @PutMapping("/me")
    public R<Boolean> updateCurrentUser(@RequestBody User user) {
        boolean result = userService.updateById(user);
        return result ? R.success(true).add("message", MessageConstant.USER_UPDATE_SUCCESS) : R.error(MessageConstant.UPDATE_FAILED);
    }
    
    /**
     * 修改密码
     */
    @PostMapping("/change-password")
    public R<Boolean> changePassword(@RequestParam Long userId,
                                     @RequestParam String oldPassword,
                                     @RequestParam String newPassword) {
        User user = userService.getById(userId);
        if (user == null) {
            return R.error(MessageConstant.USER_NOT_EXIST);
        }
        boolean matches = passwordEncoder != null ? passwordEncoder.matches(oldPassword, user.getPassword()) : oldPassword.equals(user.getPassword());
        if (!matches) {
            return R.error(MessageConstant.PASSWORD_ERROR);
        }
        user.setPassword(passwordEncoder != null ? passwordEncoder.encode(newPassword) : newPassword);
        boolean result = userService.updateById(user);
        return result ? R.success(true).add("message", MessageConstant.OPERATION_SUCCESS) : R.error(MessageConstant.UPDATE_FAILED);
    }
    
    /**
     * 管理员：分页查询用户列表（可按角色过滤）
     */
    @GetMapping("/list")
    public R<java.util.List<User>> listUsers(@RequestParam Integer page,
                                             @RequestParam Integer size,
                                             @RequestParam(required = false) String role,
                                             @RequestParam(required = false) String keyword) {
        // 使用缓存查询用户列表
        java.util.List<User> all = userService.getUserList(role, keyword);
        int from = Math.max(0, (page - 1) * size);
        int to = Math.min(all.size(), from + size);
        java.util.List<User> pageList = from < to ? all.subList(from, to) : java.util.Collections.emptyList();
        return R.success(pageList).add("total", all.size());
    }
}